from bson import ObjectId
from .. import db
from datetime import datetime

class Role:
    # 权限常量
    VIEW = 'view'           # 查看
    MANAGE_FIELDS = 'manage_fields'     # 管理农田
    MANAGE_DEVICES = 'manage_devices'   # 管理设备
    MANAGE_TASKS = 'manage_tasks'       # 管理任务
    MANAGE_USERS = 'manage_users'       # 管理用户
    MANAGE_ROLES = 'manage_roles'       # 管理角色
    ALL = 'all'            # 所有权限

    # 预定义角色
    ROLES = {
        'viewer': {
            'name': '查看者',
            'permissions': [VIEW]
        },
        'manager': {
            'name': '经理',
            'permissions': [VIEW, MANAGE_FIELDS, MANAGE_DEVICES, MANAGE_TASKS]
        },
        'admin': {
            'name': '管理员',
            'permissions': [VIEW, MANAGE_FIELDS, MANAGE_DEVICES, MANAGE_TASKS, MANAGE_USERS, MANAGE_ROLES]
        }
    }

    def __init__(self, name, permissions=None, id=None):
        self.id = id if id is not None else len(db.roles) + 1
        self.name = name
        self.permissions = permissions or []
        self.created_at = datetime.utcnow()
    
    def save(self):
        """保存角色"""
        if not hasattr(self, 'id'):
            self.id = len(db.roles) + 1
        if self not in db.roles:
            db.roles.append(self)
        return self
    
    @staticmethod
    def find_by_name(name):
        """通过名称查找角色"""
        for role in db.roles:
            if role.name == name:
                return role
        return None
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'permissions': self.permissions,
            'created_at': self.created_at.isoformat()
        }

    @staticmethod
    def init_roles():
        """初始化角色"""
        for role_id, (role_name, role_data) in enumerate(Role.ROLES.items(), 1):
            if not Role.find_by_name(role_name):
                Role(
                    id=role_id,
                    name=role_name,
                    permissions=role_data['permissions']
                ).save()

    @staticmethod
    def find_by_id(role_id):
        try:
            role_data = db.roles.find_one({'_id': ObjectId(role_id)})
            if role_data:
                return Role(
                    name=role_data['name'],
                    permissions=role_data.get('permissions', []),
                    id=role_data['_id']
                )
        except:
            return None
        return None 